package com.hzsk.lisence.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzsk.lisence.config.myexception.BaseException;
import com.hzsk.lisence.entity.EmDeviceRelationEntity;
import com.hzsk.lisence.entity.EmProducePlanEntity;
import com.hzsk.lisence.entity.EmSoftwareRelationEntity;
import com.hzsk.lisence.entity.request.NcProduceRequest;
import com.hzsk.lisence.entity.response.NcProduceDetail;
import com.hzsk.lisence.enums.ChannelEnum;
import com.hzsk.lisence.enums.FunctionItemEnum;
import com.hzsk.lisence.mapper.EmDeviceRelationMapper;
import com.hzsk.lisence.mapper.EmSoftwareRelationMapper;
import com.hzsk.lisence.service.EmProducePlanService;
import com.hzsk.lisence.service.EmRelationBindService;
import com.hzsk.lisence.strategy.FunctionListStrategy;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Date : 2024/8/21
 * @Author : ChenJin
 * @Version : v1.0.0
 **/
@Service
public class EmRelationBindServiceImpl implements EmRelationBindService {

    @Autowired
    private Map<String,FunctionListStrategy> functionListStrategyMap;
    
    @Resource
    private EmSoftwareRelationMapper emSoftwareRelationMapper;
    
    @Resource
    private EmDeviceRelationMapper emDeviceRelationMapper;
    
    @Resource
    private EmProducePlanService emProducePlanService;
    
    @Override
    @Transactional
    public Boolean syncSoftwareRelation(EmSoftwareRelationEntity emSoftwareRelationEntity) throws BaseException {
        if (ObjectUtils.isEmpty(emSoftwareRelationEntity)){
            throw new BaseException("请求参数有误");
        }
        if (StringUtils.isEmpty(emSoftwareRelationEntity.getSoftwareInfoId())||
                StringUtils.isEmpty(emSoftwareRelationEntity.getNcMaterialCode())||
                StringUtils.isEmpty(emSoftwareRelationEntity.getOsVersion())||
                StringUtils.isEmpty(emSoftwareRelationEntity.getSoftwareVersion())){
            throw new BaseException("请求参数有误");
        }
        Boolean checkFunctions = checkFunctions(emSoftwareRelationEntity.getProdType(),emSoftwareRelationEntity.getChannelNum(),emSoftwareRelationEntity.getFunctions());
        if (!checkFunctions){
            throw new BaseException("授权功能项有误");
        }
        EmSoftwareRelationEntity softwareRelation = emSoftwareRelationMapper.selectSoftwareRelationBySoftwareInfoId(emSoftwareRelationEntity);
        if (0==emSoftwareRelationEntity.getOperationType()){
            if (!ObjectUtils.isEmpty(softwareRelation)){
                throw new BaseException("软件绑定关系已存在，新增失败");
            }
            emSoftwareRelationMapper.insertSoftwareRelationEntity(emSoftwareRelationEntity);
        }else if (1==emSoftwareRelationEntity.getOperationType()){
            if (ObjectUtils.isEmpty(softwareRelation)){
                throw new BaseException("软件绑定关系不存在，修改失败");
            }
            emSoftwareRelationEntity.setId(softwareRelation.getId());
            emSoftwareRelationMapper.updateSoftwareRelationEntity(emSoftwareRelationEntity);
        }else {
            if (ObjectUtils.isEmpty(softwareRelation)){
                throw new BaseException("软件绑定关系不存在，删除失败");
            }
            emSoftwareRelationEntity.setId(softwareRelation.getId());
            emSoftwareRelationMapper.deleteSoftwareRelationEntity(emSoftwareRelationEntity);
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean syncDeviceRelation(EmDeviceRelationEntity emDeviceRelationEntity) throws BaseException {
        if (ObjectUtils.isEmpty(emDeviceRelationEntity)){
            throw new BaseException("请求参数有误");
        }
        if(StringUtils.isEmpty(emDeviceRelationEntity.getProductCode())||
                StringUtils.isEmpty(emDeviceRelationEntity.getIpcProductCode())||
                StringUtils.isEmpty(emDeviceRelationEntity.getIdcProductCode())){
            throw new BaseException("请求参数有误");
        }
        //根据NC工单号查询NC数控装置生产计划和软件绑定关系
        EmProducePlanEntity emProducePlanEntity = emProducePlanService.getProducePlan(emDeviceRelationEntity.getOrderCode());
        int count = emDeviceRelationMapper.selectCountByOrderCode(emDeviceRelationEntity);
        if (count>=emProducePlanEntity.getQuantity()){
            throw new BaseException("数控装置制作超出限制");
        }
        emDeviceRelationEntity.setNcMaterialCode(emProducePlanEntity.getNcMaterialCode());
        emDeviceRelationEntity.setMcpMaterialCode(emProducePlanEntity.getMcpMaterialCode());
        emDeviceRelationEntity.setOsId(emProducePlanEntity.getOsId());
        emDeviceRelationEntity.setOsVersion(emProducePlanEntity.getOsVersion());
        emDeviceRelationEntity.setSoftwareId(emProducePlanEntity.getSoftwareId());
        emDeviceRelationEntity.setSoftwareVersion(emProducePlanEntity.getSoftwareVersion());
        emDeviceRelationEntity.setResolution(emProducePlanEntity.getResolution());
        emDeviceRelationEntity.setProdType(emProducePlanEntity.getProdType());
        emDeviceRelationEntity.setChannelNum(emProducePlanEntity.getChannelNum());
        emDeviceRelationEntity.setFunctions(emProducePlanEntity.getFunctions());
        emDeviceRelationEntity.setStatus(0);
        //保存产品绑定关系
        EmDeviceRelationEntity emDeviceRelation = emDeviceRelationMapper.selectDeviceRelastionByNcAndIpcAndIdc(emDeviceRelationEntity);
        if (!ObjectUtils.isEmpty(emDeviceRelation)){
            //原绑定关系弃用
            emDeviceRelation.setStatus(5);
            emDeviceRelationMapper.updateDeviceRelationStatus(emDeviceRelation);
        }
        emDeviceRelationMapper.insertDeviceRelationEntity(emDeviceRelationEntity);
        if (count+1 >= emProducePlanEntity.getQuantity()){
            emProducePlanEntity.setStatus(1);
            emProducePlanService.updatePlanStatus(emProducePlanEntity);
        }
        return true;
    }

    @Override
    public PageInfo<EmDeviceRelationEntity> getNcProduceList(NcProduceRequest ncProduceRequest) throws BaseException {
        PageHelper.startPage(ncProduceRequest.getPageNum(),ncProduceRequest.getPageSize());
        List<EmDeviceRelationEntity> ncProduceDetailList = emDeviceRelationMapper.selectNcProduceList(ncProduceRequest);
        ncProduceDetailList = ncProduceDetailList.stream().map(item->{
            item.setIpcProductCode(null);
            item.setIdcDeviceId(null);
            return item;
        }).collect(Collectors.toList());
        return new PageInfo<>(ncProduceDetailList);
    }

    @Override
    @Transactional
    public Boolean updateDeviceRelation(EmDeviceRelationEntity emDeviceRelationEntity) throws BaseException {
        Boolean checkFunctions = checkFunctions(emDeviceRelationEntity.getProdType(),emDeviceRelationEntity.getChannelNum(),emDeviceRelationEntity.getFunctions());
        if (!checkFunctions){
            throw new BaseException("授权功能项有误");
        }
        //当前绑定关系弃用
        emDeviceRelationEntity.setStatus(5);
        emDeviceRelationMapper.updateDeviceRelationStatus(emDeviceRelationEntity);
        //新的绑定关系
        EmDeviceRelationEntity newDeviceRelation = new EmDeviceRelationEntity();
        BeanUtils.copyProperties(emDeviceRelationEntity,newDeviceRelation);
        newDeviceRelation.setId(null);
        newDeviceRelation.setStatus(2);
        emDeviceRelationMapper.insertDeviceRelationEntity(newDeviceRelation);
        return true;
    }

    @Override
    @Transactional
    public Boolean updateDeviceRelationStatus(EmDeviceRelationEntity emDeviceRelationEntity) throws BaseException {
        emDeviceRelationMapper.updateDeviceRelationStatus(emDeviceRelationEntity);
        return true;
    }

    @Override
    public EmDeviceRelationEntity getDeviceRelationByIdcProductCode(String idcProductCode) throws BaseException {
        List<EmDeviceRelationEntity> relations = emDeviceRelationMapper.getDeviceRelationByIdcProductCode(idcProductCode);
        if (CollectionUtils.isEmpty(relations)){
            throw new BaseException("暂无产品绑定关系");
        }
        return relations.get(0);
    }

    private Boolean checkFunctions(String prodType,String channelNum,String functions) throws BaseException {
        Boolean result = true;
        Collection<FunctionListStrategy> strategyCollection = functionListStrategyMap.values();
        for (FunctionListStrategy strategy : strategyCollection) {
            if (strategy.shouldCheck(prodType)) {
                result = strategy.check(channelNum, functions);
                break;
            }
        }
        return result;
    }
}
